package cn.fanqinghong.ymcc.mq.consumer;

import cn.fanqinghong.ymcc.constants.MessageConstants;
import cn.fanqinghong.ymcc.domain.MessageStation;
import cn.fanqinghong.ymcc.dto.StationMessageDto;
import cn.fanqinghong.ymcc.exception.GlobalException;
import cn.fanqinghong.ymcc.service.IMessageStationService;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.resources.Messages;

import java.util.ArrayList;
import java.util.Date;

/**
 * FAN
 * 2022/7/25  11:54
 */
@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = MessageConstants.STATION_CONSUMER_GROUP,
        topic = MessageConstants.STATION_TOPIC,
        selectorExpression = MessageConstants.STATION_TAGES
)
public class MessageStationConsumer  implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageStationService messageStationService;

    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        try {
            String jsonStr = new String(message.getBody(), CharsetUtil.UTF_8);
            //把接收到的消息转为MediaFile格式
            StationMessageDto stationMessageDto = JSONObject.parseObject(jsonStr, StationMessageDto.class);
            log.info("发送消息"+ stationMessageDto.getType() + ":" + stationMessageDto.getTitle() + stationMessageDto.getContent());
            //保存消息到数据库
            saveStationMessage(stationMessageDto);
            //发送站内信


        } catch (Exception e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("短信发送失败");
        }
    }

    private void saveStationMessage(StationMessageDto stationMessageDto) {
        Date date = new Date();
        stationMessageDto.getDtos().forEach(user ->{
            MessageStation messageStation = new MessageStation();
            messageStation.setSendTime(date);
            messageStation.setType(stationMessageDto.getType());
            messageStation.setTitle(stationMessageDto.getTitle());
            messageStation.setContent(stationMessageDto.getContent());
            messageStation.setUserId(user.getId());
            messageStationService.insert(messageStation);
        });
    }
}
